#include "StdAfx.h"
#include "TinyServerDefine.h"
#include "TinyCCClientMgr.h"
#include "TinyCC_Define.h"

namespace RuntimeMgr{

CTinyCCClientMgr::CTinyCCClientMgr(void)
{
	g_TimerPool.requestTimer(this,m_connectionCheckTimer,&RuntimeMgr::CTinyCCClientMgr::processTimer,9000,true);
}

CTinyCCClientMgr::~CTinyCCClientMgr(void)
{
}

CTinyInstanceRT* CTinyCCClientMgr::getInstanceByName(std::string name)
{
	return NULL;
}

CTinyUser* CTinyCCClientMgr::getUserByName(std::string name)
{
	std::map<std::string,CTinyUser*>::iterator it;
	if((it = m_UserMap.find(name))!= m_UserMap.end())
	{
		return it->second;
	}
	else
		return NULL;
}

bool CTinyCCClientMgr::ProcessReceivedMsg(CTinyMsg& inMsg,CTinyMsg& OutMsg)
{
	if(inMsg.getMsgIndex() == CLIENTMGR)
	{
		switch (inMsg.getMsgItem())
		{
		case CLIENTLOGON_REQUEST:
			{
				SingleRegionLogon(inMsg,OutMsg);
			}break;
		case CLIENTLOGOFF_REQUEST:
			{
				//logoff
			}break;
		default:
			break;
		}
		return true;
	}

	if(inMsg.getMsgIndex() == CLIENT_ACTION)
	{
		std::string username ;
		inMsg.getDefaultParamByIndex(CLIENTLOGON_USERNAME,username);
		std::map<std::string,CTinyUser*>::iterator it;
		if((it = m_UserMap.find(username))!= m_UserMap.end())
		{
			it->second->ProcessReceivedMsg(inMsg,OutMsg);
		}
		return true;
	}
	if(inMsg.getMsgIndex() == VOICECARD_ACTION)
	{
		return false;
	}
	return false;
}

bool CTinyCCClientMgr::SingleRegionLogon(CTinyMsg& inMsg,CTinyMsg& OutMsg)
{
	g_TinyCCDBMgr.ProcessReceivedMsg(inMsg,OutMsg);

	if(OutMsg.getMsgItem() == CLIENTLOGON_SUCC )
	{
		std::string name;
		inMsg.getDefaultParamByIndex(CLIENTLOGON_USERNAME,name);
		//if user exist,update socketID only
		std::map<std::string,CTinyUser*>::iterator  it = m_UserMap.find(name);
		if(it!=m_UserMap.end())
		{
			it->second->initByMsg(inMsg);
		}
		else
		{
			CTinyUser* user = new CTinyUser();
			user->initByMsg(inMsg);
			inMsg.getDefaultParamByIndex(CLIENTLOGON_USERNAME,name);
			m_UserMap.insert(std::pair<std::string,CTinyUser*>(name,user));
		}
		//if module
	}

	return true;
}

}
void RuntimeMgr::CTinyCCClientMgr::processTimer(std::string timerID)
{
	//Lock lock(this);
	//switch timerid and procss it
	for(std::map<std::string,CTinyUser*>::iterator it = m_UserMap.begin();it!= m_UserMap.end();)
	{                    
		if(g_TinyTCPIF.isConnected(it->second->getSocketID())== false)
		{
			m_UserMap.erase(it++);
		}
		else
			it++;
	}
	int i = 0;
}
